<?php

class SelectField extends Object
{
    var $Type = 'SelectField';    
    
    var $_Name;
    var $_Title;
    var $_Recordset;
    var $_FValue;
    var $_Mode;
    var $_FLabel;
    var $_Default;
    var $_Description;

    function __construct(&$form, $name, $title,  $recordset, $fvalue, $required = false, $flabel = '', $default = '', $description = '')
    {
        $this->_Name        = $name;
        $this->_Title       = $title;
        $this->_Recordset   = $recordset; // DAL Recordset
        $this->_FValue      = $fvalue; // Field to be used for the list values
        $this->_Mode        = $required?'required':'normal';
        $this->_FLabel      = $flabel; // Field to be used for the list labels
        $this->_Default     = $default; // The default selected list item (matched against the list values)
        $this->_Description = $description;                
    }
       
    function Validate()
    {
        if ($this->_Mode == 'required')
        {
            // Ensure one of the list items was selected
            if (!isset($_POST[$this->_Name]) || (strlen($_POST[$this->_Name]) == 0))
            {
                $this->_Mode  = 'error';
                return false;
            }

            // Field is valid
            $this->_Default = $_POST[$this->_Name];
            return true;
        }
        else
        {
            $this->_Default = $_POST[$this->_Name];
            return true;
        }
    }

    function ToArray()
    {
        /*
         * Generate the value => label key pairs for the list
         * as well as select the default value.
         */
        
        $data = array();
        
        while ($r = $this->_Recordset->FetchRow('ASSOC'))
            $data[] = array('value'    => $r[$this->_FValue],
                            'label'    => $r[$this->_FLabel],
                            'selected' => ($r[$this->_FValue] == $this->_Default)?'yes':'no');
        
        // Return the final field data                            
        return array('type'        => 'SelectField',
                     'name'        => $this->_Name,
                     'title'       => $this->_Title,
                     'description' => $this->_Description,
                     'mode'        => $this->_Mode,
                     'data'        => $data);
    }
}

?>